package it.polimi.traveldream.beans;

import it.polimi.traveldream.dto.CartPackageDTO;
import it.polimi.traveldream.dto.ScheduleDTO;
import it.polimi.traveldream.ejb.CustomerManager;
import it.polimi.traveldream.ejb.DefaultPackageManager;
import it.polimi.traveldream.ejb.ProductManager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name = "sharedPackageBean")
@ViewScoped
public class SharedPackageBean {

	@EJB
	private DefaultPackageManager packageManager;

	@EJB
	private ProductManager productManager;

	@EJB
	private CustomerManager customerManager;

	private CartPackageDTO pack;

	public SharedPackageBean() {
	}

	@PostConstruct
	public void init() {
		Map<String, String[]> params = FacesContext.getCurrentInstance().getExternalContext()
				.getRequestParameterValuesMap();
		String[] values = params.get("model");
		this.pack = new CartPackageDTO(this.packageManager.findPackage(Integer.valueOf(values[0])));
		values = params.get("date");
		this.pack.setDate(new Date(Long.valueOf(values[0])));
		values = params.get("duration");
		this.pack.setDuration(Integer.valueOf(values[0]));
		values = params.get("accomodation");
		this.pack.setAccomodation(this.productManager.getAccomodation(Integer.valueOf(values[0])));
		values = params.get("going");
		this.pack.setGoing(this.productManager.getTransport(Integer.valueOf(values[0])));
		values = params.get("back");
		this.pack.setBack(this.productManager.getTransport(Integer.valueOf(values[0])));
		values = params.get("schedule");
		this.pack.setSchedule(new HashMap<Integer, ScheduleDTO>());
		for (String s : values) {
			String[] sched = s.split("-");
			this.pack.addSchedule(new ScheduleDTO(Integer.valueOf(sched[0]), this.productManager
					.getActivity(Integer.valueOf(sched[1]))));
		}
	}

	public String addToCart() {
		this.customerManager.addToCart(this.pack);
		return "/customer/cart?faces-redirect=true";
	}

	public String addToGiftlist() {
		this.customerManager.addToGiftlist(this.pack);
		return "/giftList?faces-redirect=true";
	}

	public CartPackageDTO getPack() {
		return this.pack;
	}

	public void setPack(CartPackageDTO pack) {
		this.pack = pack;
	}

	public List<ScheduleDTO> getActivityList() {
		return new ArrayList<>(this.pack.getSchedule().values());
	}

}
